<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Area;
use App\Http\Resources\AreaResource;
use DB;

class AreaController extends Controller {

    protected $message = [
        'province.required' => '省级区域不能为空',
        // 'province.exists' => '省级区域不存在，请先添加',
        'AreaName.required' => '区域名称必须',
        'AreaName.max' => '区域名称不能超过60个字符',
        'AreaName.unique' => '区域名称已添加',
        'Co_ID.required' => '所属公司必须',
    ];

    /**
     * @api {get} /area/ 列表
     * @apiDescription 区域列表
     * @apiGroup 区域
     * @apiPermission none
     * @apiSuccess {String} code 状态标志 
     * @apiSuccess {String} message 提示信息 
     * @apiSuccess {Object[]} data  区域数据
     * @apiSuccessExample {json} 成功:
     *     HTTP/1.1 201
     *     {
     *         "code": 0,
     *         "message": "",
     *          "data": [
     *             {
     *               "AreaId": "区域编号",
     *               ....
     *             }
     *          ]
     *     }
     * @apiErrorExample {json} 失败:
     *     HTTP/1.1 422
     *     {
     *       "code": -1,
     *       "message": "错误提示"
     *     }
     */
    public function index(Request $request) {
        $perPage = $request->input('pageSize', 15);
        $name = $request->input('AreaName', '');
        $query = Area::query();
        if (!empty($name)) {
            $query->where('AreaName', 'like', trim($name) . '%');
        }
        $all = $request->input('total', true);
        if ($all) {
            $query->where('Fid', '>', 0);
        }
        $aid = $request->input('aid', '');
        if ($aid) {
            $aids = array_filter(explode(',', $aid));
            $query->whereIn('Fid', $aids);
        }
        
        $areaId = $request->input('dapeng', '');
        if ($areaId) {
            $query->where('AreaId', $areaId);
        }
        if($request->has('company')) {
            $cid = $request->input('company', '');
            $query->where('sy_area.Co_ID', $cid);
        }
        
        $pid = $request->input('pro', '');
        if($pid) {
           $query->where('Fid', $pid); 
        }

        $query->from('sy_area');
        $query->leftjoin('t_companycnfo as b', 'sy_area.Co_ID', '=', 'b.Co_ID');
        $query->select(['sy_area.*', 'b.Co_Name']);
        $query->with(['parentAreaName' => function($query) {
                $query->select(['AreaId', 'AreaName', 'Fid']);
            }]);
        $users = $query->paginate($perPage);

        return $users;
    }

    /**
     * @api {post} /area/ 添加
     * @apiDescription 添加区域
     * @apiGroup 区域
     * @apiPermission none
     * @apiParam {Number} province 上级区域编号
     * @apiParam {String} AreaName 区域名称
     * @apiParam {Number} Co_ID 公司编号
     * @apiSuccessExample {json} 成功:
     *     HTTP/1.1 201
     *     {
     *         "code": 0,
     *         "message": "",
     *              
     *     }
     * @apiErrorExample {json} 失败:
     *     HTTP/1.1 422
     *     {
     *       "code": -1,
     *       "message": "添加失败"
     *     }
     */
    public function store(Request $request) {
        $data = $request->input();

        $this->validate($request, [
            'AreaName' => 'required|max:60|unique:sy_area,AreaName,NULL,NULL,Co_ID,' . $data['Co_ID'],
            'province' => 'required',
            'Co_ID' => 'required',
                ], $this->message);

        $parentInfo = Area::where('AreaName', '=', trim($data['province']))
                ->where('Co_ID', '=', trim($data['Co_ID']))
                ->where('Fid', '=', 0)
                ->first();
        $ret = false;
        DB::transaction(function () use($data, $parentInfo, &$ret) {
            if (!$parentInfo) {
                $parentData = $data;
                $prefix = substr(array_get($data, 'area_code', ''), 0, 2);
               
                //$parentData['area_code'] = str_pad($prefix, 6, 0, STR_PAD_RIGHT);
                
                $parentData['AreaName'] = trim($data['province']);
                
                $parentData['area_code'] = array_get($parentData, 'parent.area_code', str_pad($prefix, 6, 0, STR_PAD_RIGHT));
                $parentData['lnglat'] = array_get($parentData, 'parent.lnglat', $data['lnglat']);
                $parentData['Fid'] = 0;
                $parentInfo = Area::create($parentData);
            }

            $parentId = $parentInfo->AreaId;

            $data['Fid'] = $parentId;
            $ret = Area::create($data);
        });

        if (!$ret) {
            $this->error('添加失败');
        }
    }

    /**
     * @api {get} /area/:id 详情
     * @apiDescription 区域信息
     * @apiGroup 区域
     * @apiPermission none
     * @apiParam {Number} id 区域编号
     * @apiSuccess {String} code 状态标志 
     * @apiSuccess {String} message 提示信息 
     * @apiSuccess {Object[]} data  区域数据
     * @apiSuccessExample {json} 成功:
     *     HTTP/1.1 201
     *     {
     *         "code": 0,
     *         "message": "",
     *          "data": {
     *              "AreaId": "区域编号",
     *               ....
     *          }
     *     }
     * @apiErrorExample {json} 失败:
     *     HTTP/1.1 422
     *     {
     *       "code": -1,
     *       "message": "错误提示"
     *     }
     */
    public function show($id) {
        return new AreaResource(Area::findOrFail($id));
    }

    /**
     * @api {put} /area/:id 更新
     * @apiDescription 更新区域
     * @apiGroup 区域
     * @apiPermission none
     * @apiParam {Number} id 区域编号
     * @apiSuccessExample {json} 成功:
     *     HTTP/1.1 201
     *     {
     *         "code": 0,
     *         "message": "",
     *              
     *     }
     * @apiErrorExample {json} 失败:
     *     HTTP/1.1 422
     *     {
     *       "code": -1,
     *       "message": "保存失败"
     *     }
     */
    public function update(Request $request, $id) {
        $area = Area::findOrFail($id);
        $data = $request->input();
        $this->validate($request, [
            'AreaName' => 'required|max:60|unique:sy_area,AreaName,' . $id . ',AreaId,Co_ID,' . $data['Co_ID'],
            'province' => 'required',
            'Co_ID' => 'required'
                ], $this->message);


        if ($area->Fid == 0) {
            return $this->error('省级区域不可更改,请添加下级区域');
        }

        $parentInfo = Area::where('AreaName', '=', trim($data['province']))
                ->where('Co_ID', '=', trim($data['Co_ID']))
                ->where('Fid', '=', 0)
                ->first();

        if (!$parentInfo) {
            $parentData = $data;
            $parentData['Fid'] = 0;
            $parentData['AreaName'] = trim($data['province']);
            $parentInfo = Area::create($parentData);
        }

        if ($parentInfo->AreaId == $id) {
            $count = Area::where('Fid', '=', $id)->count();
            if ($count > 0) {
                return $this->error('已存在下级区域,不可更改');
            }
            $data['Fid'] = 0;
        } else {
            $data['Fid'] = $parentInfo->AreaId;
        }

        if (!$area->update($data)) {
            $this->error('保存失败');
        }
    }

    /**
     * @api {delete} /destroy/:id 删除
     * @apiDescription 删除区域
     * @apiGroup 区域
     * @apiPermission none
     * @apiParam {Number} id 区域编号
     * @apiSuccessExample {json} 成功:
     *     HTTP/1.1 201
     *     {
     *         
     *          "code": 0,
     *          "message": "",
     *        
     *     }
     * @apiErrorExample {json} 失败:
     *     HTTP/1.1 422
     *     {
     *       "code": -1,
     *       "message": "已存在下级区域,不可删除"
     *     }
     */
    public function destroy($id) {

        $count = Area::where('Fid', '=', $id)->count();
        if ($count > 0) {
            return $this->error('已存在下级区域,不可删除');
        }
        $area = Area::findOrFail($id);
        if (!$area->delete()) {
             return $this->error('删除失败');
        }
        \App\Models\PriDeviceInfo::where('AreaId', '=', trim($id))->delete();
    }

}
